import React, { useEffect, useState } from "react";
import { Card, Row, Col, Form, Space, Button, InputNumber, Select, Upload } from "antd";
import XlRadio from "@/components/Form/XlRadio";
import { PlusOutlined } from "@ant-design/icons";
import { isKgsPrice, isTicketSettlement, isTsBg, isinsuranceFlag } from "@/utils/dictUtil";
import { fileUpload } from "@/services/common";
import type { UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';
import { isUps } from "@/utils/dictUtil";

const { Item } = Form;
const rules = [{required: true}];
const labelCol = {span: 3};

const OtherInfo = ({form, getDict, productInfoForm, goodsInfoForm}: any) => {
  const paymethods = getDict('paymethod');
  const customsMethods = getDict('customsMethod');
  const taxes = getDict('taxes');
  const insure = getDict('insure');
  const settlement = getDict('settlement');
  const payNode = getDict('payNode');
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const deliveryMethod = Form.useWatch('deliveryMethod', productInfoForm);
  const billMethod = Form.useWatch('billMethod', form);

  const insuranceFlag = Form.useWatch('insuranceFlag', form);
  const declaredCargoValue = Form.useWatch('declaredCargoValue', form);
  const totalWeight = Form.useWatch('totalWeight', goodsInfoForm);

  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };
  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => setFileList(newFileList);

  const uploadFileReq = ({file, filename, onSuccess, onError, data = {}}: any) => {
    const formData = new FormData();
    formData.append(filename, file);
    Object.keys(data).forEach(key => {
      formData.append(key, data?.[key]);
    })
    fileUpload(formData).then(
      res => {
        if (res?.code === '0') {
          onSuccess(res?.data);
        } else {
          onError(res?.data)
        }
      }
    )
  }

  useEffect(() => {
    // 派送方式为UPS时，报价只能为KGS；
    if (isUps(deliveryMethod)) {
      form.setFieldValue('billMethod', 'KGS');
    }
  }, [deliveryMethod]);

  useEffect(() => {
    // 报价方式按公斤时包税，按方不包税
    if (isKgsPrice(billMethod)) {
      form.setFieldValue('taxFlag', '1');
    }
  }, [billMethod]);

  // 高货值
  const isShowNotice = isinsuranceFlag(insuranceFlag) && declaredCargoValue > 0 && totalWeight > 0 && (declaredCargoValue/totalWeight >= 300);

  return (
    <Card title="其他信息" className="mt15">
      <Form form={form} labelCol={labelCol}>
        <Item label="报价方式" rules={rules} name="billMethod">
          <XlRadio.ButtonRadioGutterGroup disabled={isUps(deliveryMethod)} options={paymethods} />
        </Item>
        <Row>
          <Col span={12}>
            <Item label="报关" name="bgMethod" rules={rules} labelCol={{span: 6}}>
              <XlRadio.ButtonRadioGutterGroup options={customsMethods} />
            </Item>
          </Col>
          <Col span={12}>
            <Item noStyle shouldUpdate={(prev, next) => prev.bgMethod !== next.bgMethod}>
              {({getFieldValue}) => {
                const bgMethod = getFieldValue('bgMethod');
                if (isTsBg(bgMethod)) {
                  return (
                    <Item
                      labelCol={{span: 6}} 
                      label="报关文件" 
                      name="customsFilePath" 
                      valuePropName="fileList" 
                      extra={<Button type="text"><span style={{textDecoration: 'underline'}}>报关文件模板下载</span></Button>} 
                      getValueFromEvent={normFile}>
                      <Upload 
                        maxCount={1} 
                        customRequest={uploadFileReq}
                        onChange={handleChange}
                        fileList={fileList}
                        data={{businessCode: 'customs_file'}} 
                      >
                        {fileList.length >= 1 ? null : (
                          <Button style={{width: 200}} icon={<PlusOutlined />} type="default">上传</Button>
                        )}
                      </Upload>
                    </Item>
                  );
                }
              }}
            </Item>
          </Col>
        </Row>
        <Item label="税金" name="taxFlag" rules={[{required: true, message: '请选择是否包税'}]}>
          <XlRadio.ButtonRadioGutterGroup disabled={isKgsPrice(billMethod)} options={taxes} />
        </Item>
        <Row gutter={20}>
          <Col span={12}>
            <Item label="保险" name="insuranceFlag" labelCol={{span: 6}} rules={rules}>
              <XlRadio.ButtonRadioGutterGroup onChange={() => form.setFieldValue('declaredCargoValue', undefined)} options={insure} />
            </Item>
          </Col>
          <Col span={12}>
            <Item noStyle shouldUpdate={(prev, next) => prev.insuranceFlag !== next.insuranceFlag}>
              {({getFieldValue}) => {
                const insuranceFlag = getFieldValue('insuranceFlag');
                if (isinsuranceFlag(insuranceFlag)) {
                  return (
                    <Item label="申报货值/元" labelCol={{span: 6}}>
                      <Space>
                        <Item name="declaredCargoValue" noStyle rules={[{required: true, message: '请输入申报货值'}]} extra={<div style={{color: 'orange'}}>保费将按申报货值0.2%收取</div>}>
                          <InputNumber style={{width: 150}} />
                        </Item>
                        {isShowNotice && <span style={{color: 'red', lineHeight: '32px'}}>（高货值，需确认）</span>}
                      </Space>
                    </Item>
                  );
                }
              }}
            </Item>
          </Col>
        </Row>
        <Row gutter={20}>
          <Col span={12}>
            <Item label="结算方式" name="settlementMethod" labelCol={{span: 6}} rules={rules}>
              <XlRadio.ButtonRadioGutterGroup options={settlement} />
            </Item>
          </Col>
          <Col span={12}>
            <Item noStyle shouldUpdate={(prev, next) => prev.settlementMethod !== next.settlementMethod}>
              {({getFieldValue}) => {
                const settlementMethod = getFieldValue('settlementMethod');
                if (isTicketSettlement(settlementMethod)) {
                  return (
                    <Item labelCol={{span: 6}} label="付款节点" name="payNode" rules={rules}>
                      <Select style={{width: 250}} options={payNode} />
                    </Item>
                  );
                }
              }}
            </Item>
          </Col>
        </Row>
      </Form>
    </Card>
  );
}
export default OtherInfo;